/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cnsatmsmart.automation.mmi.controller.IO;

import cnsatmsmart.automation.mmi.controller.Buffer.Flight;
import com.itextpdf.text.BadElementException;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Kelas untuk menyimpan data pesawat ke file PDF
 * @author SIK - PTIK, BPPT
 */
public class PDFWriter {
    /** Atributes **/
    private String PDFName;
    private List<Flight> ListOfFlight;
    
    /** Constructor
     * @param FilePDF Nama file yang akan digunakan untuk mengimpan dokumen
     * @param listOfFlight List of flight yang akan disimpan ke dalam dokumen
     */
    public PDFWriter(String FilePDF, List<Flight> listOfFlight)
    {
        this.PDFName = FilePDF;
        this.ListOfFlight = listOfFlight;
    }
    
    /**
     * Inner class yang digunakan untuk menambahkan header dan footer.
     */
    static class HeaderFooter extends PdfPageEventHelper {

        public void onEndPage (PdfWriter writer, Document document) {
            /** Header **/
            Rectangle rect = writer.getBoxSize("art");
            ColumnText.showTextAligned(writer.getDirectContent(),
            Element.ALIGN_RIGHT, new Phrase("List of Aircraft - " + getTimeNow(), new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD)),
            rect.getRight(), rect.getTop(), 0);

            /** Footer **/
            ColumnText.showTextAligned(writer.getDirectContent(),
            Element.ALIGN_CENTER, new Phrase(String.format("Page %d", writer.getPageNumber()), new Font(Font.FontFamily.TIMES_ROMAN, 8, Font.BOLD)),
            (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
        }

        /**
         * Fungsi untuk mendapatkan waktu saat ini
         * Fungsi digunakan untuk menuliskan keterangan waktu pada header dokumen
         * @return Waktu saat ini dalam format DD Month YYYY HH:MM:SS
         */
        public String getTimeNow()
        {
            Calendar calendar = new GregorianCalendar();

            int date = calendar.get(Calendar.DATE);
            String month = getMonth(calendar.get(Calendar.MONTH));
            int year = calendar.get(Calendar.YEAR);
            int hour = calendar.get(Calendar.HOUR);
            int minute = calendar.get(Calendar.MINUTE);
            int second = calendar.get(Calendar.SECOND);

            if(calendar.get(Calendar.AM_PM) != 0) hour+=12;
            String TimeNow = date + " " + month + " " + year + " " + InttoString(hour)  + ":" + InttoString(minute) + ":" + InttoString(second);

            return TimeNow;
        }

        /**
         * Fungsi yang akan mengembalikan nama bulan
         * @param idx Urutan bulan, dimulai dari 0
         * @return Nama bulan dalam urutan ke- idx + 1
         */
        public String getMonth(int idx)
        {
            String[] Month = {"January", "February", "March" , "April", "May", "June", "July", "August", "September", "October", "November", "December"};
            return (Month[idx]);
        }

        /**
         * Fungsi untuk mengubah integer ke String dan menambahkan 0 di depan angka yang < 10
         * Fungsi digunakan pada getTimeNow() agar angka yang < 10 dapat menjadi dua digit
         * @param integer Angka yang akan diubah menjadi String
         * @return Hasil angka yang telah diubah formatnya menjadi String dan ditambahkan 0 didepan apabila < 10
         */
        private String InttoString(int integer){
            String temp = "0";
            if (integer < 10){
                temp += Integer.toString(integer);
            }else{
                temp = Integer.toString(integer);
            }
            return temp;
        }

    }

    /**
     * Prosedur untuk membuat dokumen PDF
     * @throws DocumentException 
     * @throws FileNotFoundException 
     * @throws BadElementException
     * @throws MalformedURLException
     * @throws IOException
     */
    public void createPdf() throws DocumentException, FileNotFoundException, BadElementException, MalformedURLException, IOException
    {
        Document document = new Document(PageSize.A4.rotate(), 50, 50, 50, 50);
        
        // creation of the different writers
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(PDFName));
        writer.setBoxSize("art", new Rectangle(36, 54, 788, 559));

        //Write header and footer first
        HeaderFooter event = new HeaderFooter();
        writer.setPageEvent(event);
        
        //Write document's content
        document.open();
        addTable(document);
        document.close();
    }

    
    
    /**
     * Prosedur untuk menambahkan tabel pada dokumen
     * @param doc
     * @throws BadElementException
     * @throws MalformedURLException
     * @throws IOException
     * @throws DocumentException
     */
    public void addTable(Document doc) throws BadElementException, MalformedURLException, IOException, DocumentException
    {
        //Fonts used in table
        Font headerFont = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);
        Font textFont = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL);

        //Number of column that used = 14, align = center
        PdfPTable table = new PdfPTable(14);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);

        //header
        PdfPCell header;
        header = new PdfPCell(new Phrase ("Status", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("State", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Code", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Call Sign", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Flag", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Country", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Lat\n(°)", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Lon\n(°)", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Alt\n(ft)", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Vertical Rate", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Track Angle\n(°)", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Ground Speed\n(knot)", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Last Update", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        header = new PdfPCell(new Phrase ("Time of Day", headerFont));
        header.setHorizontalAlignment(Element.ALIGN_CENTER);
        table.addCell(header);

        //Aircraft data in list that written to pdf
        for (int i = 0; i < ListOfFlight.size(); i++)
        {
            Image imgPlaneStatus = null;
            if (ListOfFlight.get(i).getStatus()) imgPlaneStatus = Image.getInstance(getClass().getResource("/cnsatmsmart/resources/Airplane.png"));
            else imgPlaneStatus = Image.getInstance(getClass().getResource("/cnsatmsmart/resources/circle.png"));
            table.addCell(imgPlaneStatus);

            Image imgPlaneState = null;
            if (ListOfFlight.get(i).getState() == -1) imgPlaneState = Image.getInstance(getClass().getResource("/cnsatmsmart/resources/arrow-down.png"));
            else if (ListOfFlight.get(i).getState() == 0) imgPlaneState = Image.getInstance(getClass().getResource("/cnsatmsmart/resources/arrow.png"));
            else if (ListOfFlight.get(i).getState() == 1) imgPlaneState = Image.getInstance(getClass().getResource("/cnsatmsmart/resources/arrow-up.png"));
            table.addCell(imgPlaneState);

            table.addCell(new Phrase(ListOfFlight.get(i).getCode(), textFont));
            table.addCell(new Phrase(ListOfFlight.get(i).getCallSign(), textFont));
            table.addCell(Image.getInstance(getClass().getResource("/cnsatmsmart/resources/icon/"+ListOfFlight.get(i).getCountry()+".png")));
            table.addCell(new Phrase(ListOfFlight.get(i).getCountry(), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getLatitude()), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getLongitude()), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getAltitude()), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getVerticalrate()), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getTrackangle()), textFont));
            table.addCell(new Phrase(Float.toString(ListOfFlight.get(i).getGroundSpeed()), textFont));
            table.addCell(new Phrase(ListOfFlight.get(i).getstrLastUpdate(), textFont));
            table.addCell(new Phrase(ListOfFlight.get(i).getTimeOfDay(), textFont));
        }

        doc.add(table);
    }
}
